package com.ruoyi.collect.broadcast;

import com.ruoyi.broadcast.domain.Gbhz;
import com.ruoyi.broadcast.domain.Gbss;
import com.ruoyi.broadcast.domain.GbssHistory;
import com.ruoyi.broadcast.mapper.GbhzMapper;
import com.ruoyi.broadcast.mapper.GbssHistoryMapper;
import com.ruoyi.broadcast.mapper.GbssMapper;
import com.ruoyi.common.utils.xuehua.SnowflakeIdUtils;
import com.ruoyi.control.domain.Broadcast;
import com.ruoyi.control.mapper.BroadcastMapper;
import com.ruoyi.control.service.IBroadcastService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.io.*;
import java.nio.file.*;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.stream.Stream;

@Slf4j
@Component
public class BroadcastParser {
    @Resource
    private GbhzMapper gbhzMapper;
    @Resource
    private GbssMapper gbssMapper;
    @Resource
    private GbssHistoryMapper gbssHistoryMapper;

    @Value("${collector.service.broadcast:false}")
    private boolean enable;

    @Value("${collector.disk.broadcast}")
    private String broadcast;

    private static final String SOURCE = "/home/deploy/broadcast/gbsj";
    private static final Map<String, String> copiedFiles = new HashMap<>();

    @Scheduled(cron = "0/30 * * * * ?")
    public void scheduledCopyFiles() {
        if (!enable){
            return;
        }
        Path sourceDir = Paths.get(SOURCE);
        Path targetDir = Paths.get(broadcast);
        // 确保目标目录存在
        if (!Files.exists(targetDir)) {
            try {
                Files.createDirectories(targetDir);
            } catch (IOException e) {
                // 处理创建目录时的异常
                e.printStackTrace();
                return;
            }
        }
        // 复制文件
        try (Stream<Path> stream = Files.list(sourceDir)) {
            stream.filter(Files::isRegularFile).forEach(file -> {
                try {
                    String sourceFileHash = getFileHash(file);
                    Path targetFile = targetDir.resolve(file.getFileName());

                    if (!copiedFiles.containsKey(sourceFileHash) || !Files.exists(targetFile) || !sourceFileHash.equals(getFileHash(targetFile))) {
                        Files.copy(file, targetFile, StandardCopyOption.REPLACE_EXISTING);
                        copiedFiles.put(sourceFileHash, sourceFileHash);
                    } else {
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static String getFileHash(Path file) throws IOException, NoSuchAlgorithmException {
        MessageDigest digest = MessageDigest.getInstance("SHA-256");
        try (FileInputStream fis = new FileInputStream(file.toFile())) {
            byte[] byteArray = new byte[1024];
            int bytesCount;
            while ((bytesCount = fis.read(byteArray)) != -1) {
                digest.update(byteArray, 0, bytesCount);
            }
        }
        byte[] bytes = digest.digest();
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            sb.append(String.format("%02x", b));
        }
        return sb.toString();
    }
    @Scheduled(cron = "0/30 * * * * ?")
    public void parser() {
        if (!enable) {
            return;
        }
        File folder = new File(broadcast);
        // 检查是否为文件夹
        if (!folder.exists() || !folder.isDirectory()) {
            return;
        }
        // 获取文件夹下的所有文件和子文件夹
        File[] files = folder.listFiles();
        if (files != null) {
            for (File file : files) {
                // 如果是文件，则检查文件名前缀并读取内容
                if (file.isFile()) {
                    String fileName = file.getName();
                    if (fileName.startsWith("GBHZ") || fileName.startsWith("GBSS")) {
                        try {
                            // 根据文件名前缀处理文件内容
                            if (fileName.startsWith("GBHZ")) {
                                analyzeGbhz(file);
                            } else if (fileName.startsWith("GBSS")) {
                                analyzeGbss(file);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }
    protected String getDatum(String[] data, int index) {
        if (data == null || data.length <= index) {
            log.warn("null[{}]: {}", data, index);
            return null;
        }
        String datum = data[index];
        if (!StringUtils.hasText(datum)) {
            log.warn("empty[{}]: {}", data, index);
        }
        return datum.trim();
    }
    private String getStatus(final String status) {
        if (status == null) {
            return "";
        }
        switch (status) {
            case "0":
                return "未知";
            case "1":
                return "正常";
            case "2":
                return "故障";
            case "3":
                return "广播";
        }
        return "";
    }
    private void analyzeGbhz(File file) throws Exception {
        try (BufferedReader br = new BufferedReader(new FileReader(file))) {
            String line;
            while ((line = br.readLine()) != null) {
                // 处理GBHZ文件的每一行内容
                String[] parts = line.split(";");
                if (parts.length < 4) {
                    // 如果字段数量不足，跳过该行
                    continue;
                }
                String mineCode = getDatum(parts, 0);
                String systemType = getDatum(parts, 1);
                String stationCode = getDatum(parts, 2);
                String stationAddress = getDatum(parts, 3);
                Gbhz gbhz = new Gbhz();
                if (parts.length == 4){
                    String mediaAddress = getDatum(parts, 4);
                    gbhz.setMediaAddress(mediaAddress);
                }
                gbhz.setMineCode(mineCode);
                gbhz.setStationAddress(stationAddress);
                gbhz.setSystemType(systemType);
                gbhz.setStationCode(stationCode);
                gbhz.setDataTime(new Date());
                Gbhz gbhzDb = gbhzMapper.selectGbhzByBroadcastByStationCode(gbhz.getStationCode());
                if (gbhzDb != null) {
                    gbhz.setBroadcastId(gbhzDb.getBroadcastId());
                    gbhzMapper.updateGbhz(gbhz);
                } else {
                    gbhz.setBroadcastId(String.valueOf(new SnowflakeIdUtils(5, 8).nextId()));
                    gbhzMapper.insertGbhz(gbhz);
                }
            }
        } catch (Exception e) {
            // 异常处理
            log.error("处理GBHZ文件时出错", e);
        } finally {
            // 确保文件被删除
            if (file.delete()) {
                log.info("文件 {} 已删除", file.getName());
            } else {
                log.warn("无法删除文件 {}", file.getName());
            }
        }
    }

    private void analyzeGbss(File file) throws Exception {
        try (BufferedReader br = new BufferedReader(new FileReader(file))) {
            String line;
            while ((line = br.readLine()) != null) {
                // 处理GBHZ文件的每一行内容
                String[] parts = line.split(";");
                if (parts.length < 4) {
                    // 如果字段数量不足，跳过该行
                    continue;
                }
                String mineCode = getDatum(parts, 0);
                String systemType = getDatum(parts, 1);
                String stationCode = getDatum(parts, 2);
                String stationStatus = getStatus(getDatum(parts, 3));

                Gbss gbss = new Gbss();
                gbss.setMineCode(mineCode);
                gbss.setSystemType(systemType);
                gbss.setStationCode(stationCode);
                gbss.setStationStatus(stationStatus);
                gbss.setUpdateTime(new Date());
                gbss.setBroadcastRealId(String.valueOf(new SnowflakeIdUtils(5, 8).nextId()));
                Gbss gbssDb = gbssMapper.selectGbssByBroadcastRealByStationCode(gbss.getStationCode());
                if (gbssDb != null) {
                    gbss.setBroadcastRealId(gbssDb.getBroadcastRealId());
                    gbssMapper.updateGbss(gbss);
                } else {
                    gbssMapper.insertGbss(gbss);
                }
                GbssHistory gbssHistory = new GbssHistory();
                BeanUtils.copyProperties(gbss, gbssHistory);
                gbssHistory.setBroadcastRealId(String.valueOf(new SnowflakeIdUtils(5, 8).nextId()));
                gbssHistoryMapper.insertGbssHistory(gbssHistory);
            }
        } catch (Exception e) {
            // 异常处理
            log.error("处理GBSS文件时出错", e);
        } finally {
            // 确保文件被删除
            if (file.delete()) {
                log.info("文件 {} 已删除", file.getName());
            } else {
                log.warn("无法删除文件 {}", file.getName());
            }
        }
    }
}
